﻿using Client.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Client.ViewModel
{
    public class QueryTableViewModel:ICommandNotify.NotifyBase
    {
       
        public QueryTableViewModel()
        {
           
            QueryCommand = new ICommandNotify.Command(QueryExecute, QueryCanExecute);
            NextPageCommand = new ICommandNotify.Command(NextPageExecute, NextPageCanExecute);
            //DbContext_.
        }


        private bool NextPageCanExecute()
        {
            return true;
        }
        //分页
        private async void NextPageExecute(object obj)
        {
            var DbContext_ = HelpTools.IOC.Getobject<SqlServer.DbContext>();
            var Dialog_ = HelpTools.IOC.Getobject<MessageDialog.Dialog>();
            Dialog_.OpenDialog = true;
            DbContext_.SqlConfigstr = SelectText;
            ListTable = await Task.Run(() =>
            {
                PropertyInfo CurrentPage = obj.GetType().GetProperty("CurrentPage");
                PropertyInfo SelectedData = obj.GetType().GetProperty("SelectedData");
                string Sql = $"SELECT *, 0 AS _NAV_ORDER_F_ FROM {TableName} ORDER BY _NAV_ORDER_F_ OFFSET {CurrentPage.GetValue(obj, null)} ROWS FETCH NEXT {SelectedData.GetValue(obj, null)} ROWS ONLY";
                return DbContext_.Where(Sql).DefaultView;
            });
            Dialog_.OpenDialog = false;
        }
     
        #region 方法
        private bool QueryCanExecute()
        {
            return !string.IsNullOrWhiteSpace(SelectText);
        }

        private async void QueryExecute(object obj)
        {
            if (obj != null)
            {
                return;
            }
            var DbContext_ = HelpTools.IOC.Getobject<SqlServer.DbContext>();
            var Dialog_ = HelpTools.IOC.Getobject<MessageDialog.Dialog>();
            Dialog_.OpenDialog = true;
            DbContext_.SqlConfigstr = SelectText;
            ListData=await Task.Run(() =>
            {
              return DbContext_.Where("SELECT ROW_NUMBER() " +
           "OVER (ORDER BY t.TABLE_NAME) AS 序号, " +
           "t.TABLE_NAME AS 表名, c.value AS 注释 " +
           "FROM INFORMATION_SCHEMA.TABLES AS t LEFT JOIN " +
           "sys.extended_properties AS c ON OBJECT_ID(t.TABLE_NAME) = c.major_id  " +
           "AND c.minor_id = 0 AND c.name = 'MS_Description'").AsEnumerable().AsQueryable().Select(o => new
                {
                    序号 = o.Field<Int64>("序号"),
                    表名 = o.Field<string>("表名"),
                    注释 = o.Field<string>("注释")
                }).ToList();
            });
            Dialog_.OpenDialog = false;
        }
        /// <summary>
        /// 打开数据表
        /// </summary>
        private async void SelectedItemsExecute(object parameter)
        {
            var DbContext_ = HelpTools.IOC.Getobject<SqlServer.DbContext>();
            var Dialog_ = HelpTools.IOC.Getobject<MessageDialog.Dialog>();
            PropertyInfo property = parameter.GetType().GetProperty("表名");
            TableName = property.GetValue(parameter, null) as string;
            Dialog_.OpenDialog = true;
            DbContext_.SqlConfigstr = SelectText;
            var data=await Task.Run(() =>
            {
                
                string Sql = "";
                if (string.IsNullOrWhiteSpace(BillNo))
                {
                    Sql = $"SELECT *, 0 AS _NAV_ORDER_F_ FROM {TableName} ORDER BY _NAV_ORDER_F_ OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY";
                }
                else
                {
                    Sql = $"SELECT * FROM {TableName} WHERE BillNo='{BillNo}'";
                }
                int count =  DbContext_.Count($"SELECT Count(1) AS count  FROM  {TableName}  ");
                var dataList= DbContext_.Where(Sql).DefaultView;
                return new {
                    Count = count,
                    dataList= dataList,
                };
            });
            ListTable = data.dataList;
            PaginModel_ = new PaginModel()
            {
                Total = data.Count,
                TotalPage = data.Count/10,
                CurrentPage=1
            };
            Dialog_.OpenDialog = false;
        }
        /// <summary>
        /// 根据datatable获得列名
        /// </summary>
        /// <param name="dt">表对象</param>
        /// <returns>返回结果的数据列数组</returns>
        public  string[] GetColumnsByDataTable(DataTable dt)
        {
            string[] strColumns = null;
            if (dt.Columns.Count > 0)
            {
                int columnNum = 0;
                columnNum = dt.Columns.Count;
                strColumns = new string[columnNum];
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    strColumns[i] = dt.Columns[i].ColumnName;
                }
            }
            return strColumns;
        }
        #endregion
        #region 命令
        public ICommandNotify.Command QueryCommand { get; set; }
        public ICommandNotify.Command NextPageCommand { get; set; }//下一页

        #endregion
        #region 属性
        private DataView ListTable_;

        public DataView ListTable
        {
            get { return ListTable_; }
            set { ListTable_ = value;
                SetProperty(ref ListTable_, ListTable);
            }
        }


        private IEnumerable<object> ListData_;

        public IEnumerable<object> ListData
        {
            get { return ListData_; }
            set { ListData_ = value;
                SetProperty(ref ListData_, ListData);
            }
        }

        private Dictionary<string,string> DatabaseType_;
        /// <summary>
        /// 数据库枚举
        /// </summary>
        public Dictionary<string,string> DatabaseType
        {
            get   
            {
                if(DatabaseType_ == null|| DatabaseType_.Count == 0)
                {
                    DatabaseType_ = new Dictionary<string,string>();
                    var IConfiguration_ = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>();
                    foreach (var item in IConfiguration_.GetSetUpModel())
                    {
                        // string? connet=  item?.ConnectingString?.Split(";")?.Where(o => o.Contains("Catalog"))?.FirstOrDefault()?.Split("=")[1];
                        if (item.DatabaseName == null|| item.ConnectingString==null) continue;
                        DatabaseType_.Add(item.DatabaseName, item.ConnectingString);
                    } 
                }
                return DatabaseType_;
            }
            set { DatabaseType_ = value; }
        }

        private string SelectText_;
        /// <summary>
        /// 选择的数据数据库
        /// </summary>
        public string SelectText
        {
            get { return SelectText_; }
            set { SelectText_ = value; }
        }
        private string BillNo_;
        /// <summary>
        /// 输入的单据数据
        /// </summary>
        public string BillNo
        {
            get { return BillNo_; }
            set { BillNo_ = value; }
        }

        private object SelectedItems_;

        public object SelectedItems
        {
            get {
                if (SelectedItems_ != null) SelectedItemsExecute(SelectedItems_);
                return SelectedItems_; 
            
            }
            set { SelectedItems_ = value; }
        }

        private string TableName_;

        public string TableName
        {
            get { return TableName_; }
            set { TableName_ = value; }
        }
        private PaginModel PaginModel;

        public PaginModel PaginModel_
        {
            get { return PaginModel; }
            set {
                PaginModel = value;
                SetProperty(ref PaginModel, PaginModel_);
            }
        }
        #endregion
    }
}
